﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeederSerialPort
{
    /// <summary>
    /// 当前配置参数
    /// </summary>
    public class CurrentParameter
    {
        #region Private

        private int baudRate = 9600;
        private int dataBit = 8;
        private Port port;
        private CheckMode checkMode;
        private StopBit stopBit = StopBit.One;
        private SerialPort serialPort;

        private string dataReceiveInfo;
        private string sendData;
        private bool isOpen;
        private bool receiveFormat16 = true;
        private bool sendFormat16 = true;

        private int sendCount;
        private int receiveCount;

        #endregion

        #region UI绑定参数

        /// <summary>
        /// 发送数量
        /// </summary>
        public int SendCount
        {
            get { return sendCount; }
            set { sendCount = value; }
        }

        /// <summary>
        /// 接收数量
        /// </summary>
        public int ReceiveCount
        {
            get { return receiveCount; }
            set { receiveCount = value; }
        }

        /// <summary>
        /// 接收区16进制
        /// </summary>
        public bool ReceiveFormat16
        {
            get { return receiveFormat16; }
            set { receiveFormat16 = value;}
        }

        /// <summary>
        /// 接收区数据
        /// </summary>
        public string DataReceiveInfo
        {
            get { return dataReceiveInfo; }
            set { dataReceiveInfo = value; }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        public string SendData
        {
            get
            {
                return sendData;
            }
            set { sendData = value;}
        }

        /// <summary>
        /// 发送区16进制
        /// </summary>
        public bool SendFormat16
        {
            get { return sendFormat16; }
            set { sendFormat16 = value;}
        }

        #endregion

        #region 串口参数信息

        /// <summary>
        /// 开关
        /// </summary>
        public bool IsOpen
        {
            get { return isOpen; }
            set { isOpen = value;}
        }


        /// <summary>
        /// 数据位
        /// </summary>
        public int DataBit
        {
            get { return dataBit; }
            set { dataBit = value; }
        }

        /// <summary>
        /// 波特率
        /// </summary>
        public int BaudRdate
        {
            get { return baudRate; }
            set { baudRate = value;}
        }

        /// <summary>
        /// 端口
        /// </summary>
        public Port Port
        {
            get { return port; }
            set { port = value; }
        }

        /// <summary>
        /// 校验
        /// </summary>
        public CheckMode CheckMode
        {
            get { return checkMode; }
            set { checkMode = value;}
        }

        /// <summary>
        /// 停止位
        /// </summary>
        public StopBit StopBit
        {
            get { return stopBit; }
            set { stopBit = value;}
        }

        /// <summary>
        /// COM
        /// </summary>
        public SerialPort SerialPort
        {
            get { return serialPort; }
            set { serialPort = value;}
        }


        #endregion

        #region 串口操作方法

        /// <summary>
        /// 开启串口
        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            if (serialPort != null && serialPort.IsOpen)
            {
                return Close();
            }
            try
            {
                serialPort = new SerialPort();
                serialPort.DataBits = this.DataBit;
                serialPort.StopBits = ComHelper.GetStopBits(this.StopBit.ToString());
                serialPort.Parity = ComHelper.GetParity(this.CheckMode.ToString());
                serialPort.PortName = this.Port.ToString();
                serialPort.RtsEnable = true;
                serialPort.BaudRate = this.baudRate;
                serialPort.DataReceived += SerialPort_DataReceived;
                serialPort.Open();

                if (serialPort.IsOpen)
                    return IsOpen = true;
                else
                    return IsOpen = false;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
            return IsOpen = false;
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                    return IsOpen = serialPort.IsOpen;
                }
                else
                {
                    return IsOpen = serialPort.IsOpen;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                return IsOpen = false;
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        public void Send()
        {

            if (SendFormat16)
            {
                byte[] bytes = CRC.StringToHexByte(SendData);
                this.SerialPort.Write(bytes, 0, bytes.Length);
                SendCount = bytes.Length; //不做增量
            }
            else
            {
                this.SerialPort.Write(SendData);
                SendCount = SendData.Length;
            }
            //Messenger.Default.Send("", "PlaySendFlashing");
        }

        /// <summary>
        /// 清空接收区
        /// </summary>
        public void Clear()
        {
            this.DataReceiveInfo = string.Empty;
        }

        /// <summary>
        /// 清空发送区和缓存区
        /// </summary>
        public void ClearText()
        {
            this.SendData = string.Empty;
            this.SendCount = 0;
            this.ReceiveCount = 0;
        }

        #endregion

        /// <summary>
        /// 返回事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //Messenger.Default.Send("", "PlayReciveFlashing");
            //
            //byte[] readBuffer = new byte[SerialPort.ReadBufferSize];
            //SerialPort.Read(readBuffer, 0, readBuffer.Length);
            //
            //ReceiveCount = SerialPort.ReceivedBytesThreshold; //不做增量
            //
            //if (ReceiveFormat16)
            //{
            //    //不做增量
            //    DataReceiveInfo = CRC.ByteToString(readBuffer, true);
            //}
            //else
            //{
            //    DataReceiveInfo = Encoding.ASCII.GetString(readBuffer);
            //}


            byte[] ReDatas = new byte[SerialPort.BytesToRead];
            SerialPort.Read(ReDatas, 0, ReDatas.Length);//读取数据
            this.AddData(ReDatas);//输出数据

        }



        //测试方法，待整理
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] ReDatas = new byte[SerialPort.BytesToRead];
            SerialPort.Read(ReDatas, 0, ReDatas.Length);//读取数据
            this.AddData(ReDatas);//输出数据
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="data">字节数组</param>
        public void AddData(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.AppendFormat("{0:x2}" + " ", data[i]);
            }
            DataReceiveInfo += sb.ToString().ToUpper();
            //if (rbtnHex.Checked)
            //{
            //    StringBuilder sb = new StringBuilder();
            //    for (int i = 0; i < data.Length; i++)
            //    {
            //        sb.AppendFormat("{0:x2}" + " ", data[i]);
            //    }
            //    AddContent(sb.ToString().ToUpper());
            //}
            //else if (rbtnASCII.Checked)
            //{
            //    AddContent(new ASCIIEncoding().GetString(data));
            //}
            //else if (rbtnUTF8.Checked)
            //{
            //    AddContent(new UTF8Encoding().GetString(data));
            //}
            //else if (rbtnUnicode.Checked)
            //{
            //    AddContent(new UnicodeEncoding().GetString(data));
            //}
            //else
            //{ }
            //
            //lblRevCount.Invoke(new MethodInvoker(delegate
            //{
            //    lblRevCount.Text = (int.Parse(lblRevCount.Text) + data.Length).ToString();
            //}));
        }


        /// <summary>
        /// 输入到显示区域
        /// </summary>
        /// <param name="content"></param>
        //private void AddContent(string content)
        //{
        //    this.BeginInvoke(new MethodInvoker(delegate
        //    {
        //        if (chkAutoLine.Checked && txtShowData.Text.Length > 0)
        //        {
        //            txtShowData.AppendText("\r\n");
        //        }
        //        txtShowData.AppendText(content);
        //    }));
        //}

    }
}
